package liangtWorkSpace.springTest.aopCGLIBText.factory;

import liangtWorkSpace.springTest.aopCGLIBText.dao.GoodsDao;
import liangtWorkSpace.springTest.aopProxyTest.aspect.MyAspect;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author liangt
 * @ClassName: MyBeanFactory
 * @title: MyBeanFactory
 * @projectName liangtWorkSpace.springTest.aopCGLIBText.factory
 * @description: CGLIB实现动态代理
 * @date 2020/10/13 18:19
 */
public class MyBeanFactory {

    public static GoodsDao getBean(){
        //准备代理目标
        final GoodsDao goodsDao = new GoodsDao();

        //准备切点
        final MyAspect myAspect = new MyAspect();

        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(goodsDao.getClass());

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                myAspect.myBefore();
                Object obj = method.invoke(goodsDao,args);
                myAspect.myAfter();
                return obj;
            }
        });

        GoodsDao goodsDaoProx = (GoodsDao) enhancer.create();
        return goodsDaoProx;
    }
}
